'use strict';

const md5 		= require('js-md5');
const Base64  	= require('js-base64').Base64;
const cookies   = require('js-cookie');

/**
 * [appResult 统一返回值使用]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {String}   info  [description]
 * @param    {[type]}   data  [description]
 * @param    {Boolean}  err   [description]
 * @param    {Number}   error [description]
 * @return   {[type]}         [description]
 */
exports.appResult = function(info = 'ERROR',data = null,err = true,error = -1){
	return {info:info,data:data,err:err,error:error};
}

/**
 * [winWidth 获取窗口宽度]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @return   {[type]}   [description]
 */
exports.winWidth = function(){
	return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 'UNNOKW';
}
/**
 * [winHeight 获取窗口高度]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @return   {[type]}   [description]
 */
exports.winHeight = function(){
	return document.documentElement.clientHeight || document.body.clientHeight || 'UNNOKW';
}

/**
 * [md5 md5加密函数]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   str [description]
 * @return   {[type]}       [description]
 */
exports.md5 = function(str){
	try{
		return md5(str);
	} catch(err){
		console.error(err.message);
	}
	return false;
}
/**
 * [base64_decode base64解密函数]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   str [description]
 * @return   {[type]}       [description]
 */
exports.base64_decode = function(str){
	return Base64.decode(str);
}
/**
 * [base64_encode base64加密函数]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   str [description]
 * @return   {[type]}       [description]
 */
exports.base64_encode = function(str){
	return Base64.encode(str);
}
/**
 * [cookie_set 设置cookie]
 * @author        szjcomo
 * @createTime 2019-12-09
 * @param      {[type]}   name    [description]
 * @param      {[type]}   value   [description]
 * @param      {Object}   options [description]
 * @return     {[type]}           [description]
 */
exports.cookie_set = function(name,value,options = {}) {
    return cookies.set(name,value,options);
}
/**
 * [cookie_get 获取cookie]
 * @author        szjcomo
 * @createTime 2019-12-09
 * @param      {[type]}   name    [description]
 * @param      {Object}   options [description]
 * @return     {[type]}           [description]
 */
exports.cookie_get = function(name,options = {}) {
    return cookies.get(name,options);
}
/**
 * [cookie_delete 删除cookie]
 * @author        szjcomo
 * @createTime 2019-12-09
 * @param      {[type]}   name    [description]
 * @param      {Object}   options [description]
 * @return     {[type]}           [description]
 */
exports.cookie_delete = function(name,options = {}) {
    return cookies.remove(name,options);
}
/**
 * [orgCookie 获取原生的cookie对象]
 * @type {[type]}
 */
exports.orgCookie = cookies;

/**
 * [mt_rand 获取随机数]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {Number}   min [description]
 * @param    {Number}   max [description]
 * @return   {[type]}       [description]
 */
exports.mt_rand = function(min = 0.1,max = 1.0){
    try{
        let Range = max - min;
        let Rand = Math.random();  
        let num = min + Math.round(Rand * Range);
        return num;
    } catch(e){
    	console.error(e.message);
        return 0;
    }
}
/**
 * [rand_str 获取随机字符串]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {Number}   len  [description]
 * @param    {String}   type [description]
 * @return   {[type]}        [description]
 */
exports.rand_str = function(len = 4,type = 'default'){
    let that = this;
    len = len || 4;
    try{
	    let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    switch(type){
	        case 'number':
	            str = '0123456789';
	            break;
	        case 'letter':
	            str = 'abcdefghijklmnopqrstuvwxyz';
	            break;
	    }
	    let result = '';
	    for (let i=0;i<len;i++){
	        result+=str.substr(that.mt_rand(0,str.length),1);
	    }
	    return result;	    	
    } catch(err){
    	console.error(err.message);
    	return '';
    }
}
/**
 * [json_decode json反序列化]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   str [description]
 * @return   {[type]}       [description]
 */
exports.json_decode = function(str){
    if(typeof str == 'string'){
        str = str.replace(/(^\s*)|(\s*$)|(^\r)|(^\n)/g, "");
        try{
            return JSON.parse(str);
        } catch(e){
            console.error(e.message);
            return false;
        }            
    } else {
        return false;
    }
}
/**
 * [json_encode json序列化]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {Object}   obj [description]
 * @return   {[type]}       [description]
 */
exports.json_encode = function(obj = {}){
    try{
        return JSON.stringify(obj);
    } catch(e){
        console.error(e.message);
        return false;
    }
}
/**
 * [strlen 获取字符串长度]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   str [description]
 * @return   {[type]}       [description]
 */
exports.strlen = function(str){
	let len = 0;
	for (let i=0; i<str.length; i++) { 
		let c = str.charCodeAt(i); 
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
			len++; 
		} else { 
			len+=2; 
		} 
	} 
	return len;
}
/**
 * 去除空格
 * @param  {str}
 * @param  {type} 
 *       type:  1-所有空格  2-前后空格  3-前空格 4-后空格
 * @return {String}
 */
exports.trim = function(str, type = 2) {
    switch (type) {
        case 1:
            return str.replace(/\s+/g, "");
        case 2:
            return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:
            return str.replace(/(^\s*)/g, "");
        case 4:
            return str.replace(/(\s*$)/g, "");
        default:
            return str;
    }
}
/**
 * [recursion 一维数组递归成树]
 * @Author   szjcomo
 * @DateTime 2019-09-21
 * @param    {[type]}   data [description]
 * @param    {[type]}   pid  [description]
 * @return   {[type]}        [description]
 */
exports.recursion = function(data,pid,field = 'pid',pk = 'id'){
	let that = this;
	let tree = [];
	let length = data.length;
	for(let i = 0;i < length;i++){
		if(data[i][field] == pid){
			data[i]['child'] = that.recursion(data,data[i][pk],field,pk);
			tree.push(data[i]);
		}
	}
	return tree;
}

/**
 * [recursiveInversion 多维数组转一维数组]
 * @Author   szjcomo
 * @DateTime 2019-09-24
 * @param    {[type]}   data [description]
 * @return   {[type]}        [description]
 */
exports.recursiveInversion = function(data){
    let that = this;
    let result = [];
    data.forEach((item,index)=>{
        if(item.child && item.child.length > 0){
            result.push(item);
            let tmp = that.recursiveInversion(item.child);
            result = result.concat(tmp);
        } else {
            result.push(item);
        }
    })
    return result;
}

/**
 * [szjcompile 对字符串进行加密]
 * @Author   szjcomo
 * @DateTime 2019-09-24
 * @param    {[type]}   code [description]
 * @return   {[type]}        [description]
 */
exports.szj_encode = function(code){
    let result = '';
    let src = this.base64_encode(this.json_encode({code:code}));
    for(let i = 0;i< src.length;i++){
        result += String.fromCharCode(src.charCodeAt(i) + 1);
    }
    return result;
}
/**
 * [szjuncompile 自定义解密函数]
 * @Author   szjcomo
 * @DateTime 2019-09-24
 * @param    {[type]}   code [description]
 * @return   {[type]}        [description]
 */
exports.szj_decode = function(code){
    let result = '';
    for(let i = 0;i < code.length;i++){
        result += String.fromCharCode(code.charCodeAt(i) - 1);
    }
    let data = this.base64_decode(result);
    let obj = this.json_decode(data);
    return obj.code;
}



/**
 * @param  {arr} 数组
 * @param  {type} 1：从小到大   2：从大到小   3：随机
 * @return {Array}
 */
exports.arraySort = function (arr, type) {
	type = type || 1;
    return arr.sort( (a, b) => {
        switch(type) {
            case 1:
                return a - b;
            case 2:
                return b - a;
            case 3:
                return Math.random() - 0.5;
            default:
                return arr;
        }
    })
}


/**
 * [unique 数组去重]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @return   {[type]}       [description]
 */
exports.arrayUnique = function(arr) {
    if ( Array.hasOwnProperty('from') ) {
        return Array.from(new Set(arr))
    }else{
        let r = [], NaNBol = true
        for(let i=0; i < arr.length; i++) {
            if (arr[i] !== arr[i]) {
                if (NaNBol && r.indexOf(arr[i]) === -1) {
                    r.push(arr[i])
                    NaNBol = false
                }
            }else{
                if(r.indexOf(arr[i]) === -1) r.push(arr[i])
            }
        }
        return r
    }
}


/**
 * [arrayRemove 数组删除其中一个元素]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @param    {[type]}   ele [description]
 * @return   {[type]}       [description]
 */
exports.arrayRemove = function (arr, ele) {
    let index = arr.indexOf(ele);
    if(index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

/**
 * [arrayMax 数组中求最大值]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @return   {[type]}       [description]
 */
exports.arrayMax = function (arr) {
    return Math.max.apply(null, arr);
}

/**
 * [arrayMax 数组中求最小值]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @return   {[type]}       [description]
 */
exports.arrayMin = function (arr) {
    return Math.min.apply(null, arr);
}

/**
 * [arrayMax 数组中求最小值]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @return   {[type]}       [description]
 */
exports.arraySum = function (arr) {
    return arr.reduce( (pre, cur) => {
        return pre + cur
    })
}

/**
 * [arrayMax 数组中求平均值]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   arr [description]
 * @return   {[type]}       [description]
 */
exports.arrayAvg = function (arr) {
    return this.arraySum(arr)/arr.length;
}

/**
 * [strCase 字符串转大小写]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   str  [description]
 * @param    {[type]}   type [ 1:首字母大写  2：首页母小写  3：大小写转换  4：全部大写  5：全部小写]
 * @return   {[type]}        [description]
 */
exports.strCase = function (str, type = 4) {
    switch (type) {
        case 1:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
            });
        case 2:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
            });
        case 3:
            return str.split('').map( function(word){
                if (/[a-z]/.test(word)) {
                    return word.toUpperCase();
                }else{
                    return word.toLowerCase()
                }
            }).join('')
        case 4:
            return str.toUpperCase();
        case 5:
            return str.toLowerCase();
        default:
            return str;
    }
}

/**
 * [numberToChinese 将阿拉伯数字翻译成中文的大写数字]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   num [description]
 * @return   {[type]}       [description]
 */
exports.numberToChinese = function(num) {
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
    var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
        k = 0,
        re = "";
    for(var i = a[0].length - 1; i >= 0; i--) {
        switch(k) {
            case 0:
                re = BB[7] + re;
                break;
            case 4:
                if(!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
                    .test(a[0]))
                    re = BB[4] + re;
                break;
            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k = 0;
                break;
        }
        if(k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
            re = AA[0] + re;
        if(a[0].charAt(i) != 0)
            re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }
    if(a.length > 1) // 加上小数部分(如果有小数部分)
    {
        re += BB[6];
        for(var i = 0; i < a[1].length; i++)
            re += AA[a[1].charAt(i)];
    }
    if(re == '一十')
        re = "十";
    if(re.match(/^一/) && re.length == 3)
        re = re.replace("一", "");
    return re;
}

/**
 * [changeToChinese 将数字转换为大写金额]
 * @Author   szjcomo
 * @DateTime 2019-09-16
 * @param    {[type]}   Num [description]
 * @return   {[type]}       [description]
 */
exports.changeToChinese = function (Num) {
    //判断如果传递进来的不是字符的话转换为字符
    if(typeof Num == "number") {
        Num = new String(Num);
    };
    Num = Num.replace(/,/g, "") //替换tomoney()中的“,”
    Num = Num.replace(/ /g, "") //替换tomoney()中的空格
    Num = Num.replace(/￥/g, "") //替换掉可能出现的￥字符
    if(isNaN(Num)) { //验证输入的字符是否为数字
        //alert("请检查小写金额是否正确");
        return "";
    };
    //字符处理完毕后开始转换，采用前后两部分分别转换
    var part = String(Num).split(".");
    var newchar = "";
    //小数点前进行转化
    for(var i = part[0].length - 1; i >= 0; i--) {
        if(part[0].length > 10) {
            return "";
            //若数量超过拾亿单位，提示
        }
        var tmpnewchar = ""
        var perchar = part[0].charAt(i);
        switch(perchar) {
            case "0":
                tmpnewchar = "零" + tmpnewchar;
                break;
            case "1":
                tmpnewchar = "壹" + tmpnewchar;
                break;
            case "2":
                tmpnewchar = "贰" + tmpnewchar;
                break;
            case "3":
                tmpnewchar = "叁" + tmpnewchar;
                break;
            case "4":
                tmpnewchar = "肆" + tmpnewchar;
                break;
            case "5":
                tmpnewchar = "伍" + tmpnewchar;
                break;
            case "6":
                tmpnewchar = "陆" + tmpnewchar;
                break;
            case "7":
                tmpnewchar = "柒" + tmpnewchar;
                break;
            case "8":
                tmpnewchar = "捌" + tmpnewchar;
                break;
            case "9":
                tmpnewchar = "玖" + tmpnewchar;
                break;
        }
        switch(part[0].length - i - 1) {
            case 0:
                tmpnewchar = tmpnewchar + "元";
                break;
            case 1:
                if(perchar != 0) tmpnewchar = tmpnewchar + "拾";
                break;
            case 2:
                if(perchar != 0) tmpnewchar = tmpnewchar + "佰";
                break;
            case 3:
                if(perchar != 0) tmpnewchar = tmpnewchar + "仟";
                break;
            case 4:
                tmpnewchar = tmpnewchar + "万";
                break;
            case 5:
                if(perchar != 0) tmpnewchar = tmpnewchar + "拾";
                break;
            case 6:
                if(perchar != 0) tmpnewchar = tmpnewchar + "佰";
                break;
            case 7:
                if(perchar != 0) tmpnewchar = tmpnewchar + "仟";
                break;
            case 8:
                tmpnewchar = tmpnewchar + "亿";
                break;
            case 9:
                tmpnewchar = tmpnewchar + "拾";
                break;
        }
        var newchar = tmpnewchar + newchar;
    }
    //小数点之后进行转化
    if(Num.indexOf(".") != -1) {
        if(part[1].length > 2) {
            // alert("小数点之后只能保留两位,系统将自动截断");
            part[1] = part[1].substr(0, 2)
        }
        for(i = 0; i < part[1].length; i++) {
            tmpnewchar = ""
            perchar = part[1].charAt(i)
            switch(perchar) {
                case "0":
                    tmpnewchar = "零" + tmpnewchar;
                    break;
                case "1":
                    tmpnewchar = "壹" + tmpnewchar;
                    break;
                case "2":
                    tmpnewchar = "贰" + tmpnewchar;
                    break;
                case "3":
                    tmpnewchar = "叁" + tmpnewchar;
                    break;
                case "4":
                    tmpnewchar = "肆" + tmpnewchar;
                    break;
                case "5":
                    tmpnewchar = "伍" + tmpnewchar;
                    break;
                case "6":
                    tmpnewchar = "陆" + tmpnewchar;
                    break;
                case "7":
                    tmpnewchar = "柒" + tmpnewchar;
                    break;
                case "8":
                    tmpnewchar = "捌" + tmpnewchar;
                    break;
                case "9":
                    tmpnewchar = "玖" + tmpnewchar;
                    break;
            }
            if(i == 0) tmpnewchar = tmpnewchar + "角";
            if(i == 1) tmpnewchar = tmpnewchar + "分";
            newchar = newchar + tmpnewchar;
        }
    }
    //替换所有无用汉字
    while(newchar.search("零零") != -1)
        newchar = newchar.replace("零零", "零");
    newchar = newchar.replace("零亿", "亿");
    newchar = newchar.replace("亿万", "亿");
    newchar = newchar.replace("零万", "万");
    newchar = newchar.replace("零元", "元");
    newchar = newchar.replace("零角", "");
    newchar = newchar.replace("零分", "");
    if(newchar.charAt(newchar.length - 1) == "元") {
        newchar = newchar + "整"
    }
    return newchar;
}